const http = require("http");
const fs = require("fs");
const server = http.createServer((req, res) => {
  // 存请求地址
  res.setHeader("content-type", "text/html;charset=utf-8");
  
  //   这个也可以解构赋值,上下两种都可能
  // let { pathname } = new URL(req.url, "http://127.0.0.1");
  let url = new URL(req.url, "http://localhost");
  //   console.log(url.pathname);
  //   console.log(__dirname + "/public" + url.pathname);
  if (url.pathname === "/" || url.pathname === "/index.html") {
    let str = fs.readFile(
      __dirname + "/public" + "/index.html",
      (err, data) => {
        if (err) {
          console.log(data);
          return;
        }
        //   console.log(data);
        res.end(data);
      }
    );
    return;
  }
  if (url.pathname === "/admin.html") {
    let str = fs.readFile(
      __dirname + "/public" + "/admin.html",
      (err, data) => {
        if (err) {
          console.log("请求发生错误" + data);
          return;
        }
        res.end(data);
      }
    );
    return;
  }

  if (url.pathname === "/favicon.icon") {
    res.end("<h1>404</h1>");
  } else {
    res.setHeader("content-type", "text/html;charset=utf-8");
    res.end("<h1>404</h1>");
  }
});

server.listen(80, () => {
  console.log("开始监听");
});
